<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Users extends CI_Model
{
	function __construct()
	{
		parent::__construct();
	}
	
	function get_list()
	{
		$query= $this->db->get('prode_cat_user');
		//var_dump($query);
		
		if ($query->num_rows()!=0)
		{
			return $query->result_array();	
		}
		else
		{
			return false;
		}
	}
	
	function get_data($id=0)
	{ 
		$query= $this->db->get_where('prode_cat_user',array('usrId'=>$id));
		if ($query->num_rows()!=0)
		{
			return $query->row();	
		}
		else
		{
			return array();
		}
	}
	
	function insert($data=null)
	{
		if($data == null)
		{
			return false;
		}
		else
		{
			$array2 = array(
				'username'=>$data['username'],
				'email'=>$data['email'],
				'password'=>$data['pass']
				);
			
			if($this->db->insert('prode_cat_user',array(
							'usrName'=>$data['username'],
							'usrMail'=>$data['email'],
							'usrPass'=>md5($data['pass'])
							)))
				{
					
				//Obtener el id del usuario
				$usr  = 0;
				$query = $this->db->get_where('prode_cat_user', array('usrName' => $data['username'], 'usrPass'=>md5($data['pass'])));
				if ($query->num_rows()!=0)
					{
					$usr = $query->row('usrId');
					}
					
				//Obtener el id de la operacion
				$op = 0;
				$query = $this->db->get_where('prode_cat_operation', array('opCode' => 'UR'));
				if ($query->num_rows()!=0)
					{
					$op = $query->row('opId');
					}
					
				//Registrar actividad
				$this->db->insert('prode_cat_activity',array('usrId'=>$usr,'actOp'=>$op,'actDate'=>date('Y-m-d G:i:s')));
				return $array2;
				}
			else
				{
				return false;
				}

		}
	}
	
	function InsertFromFacebook($data=null)
	{
		if($data == null)
		{
			return false;
		}
		else
		{
			$isUpdate = false;
			$query = $this->db->get_where('prode_cat_user', array('fbId' => $data['usuario'][0]['uid']));
			
			$usrName = $data['user_profile']['name'];
			if(isset($data['user_profile']['username']))
			{
				if($data['user_profile']['username'] != null)
				{
					$usrName = $data['user_profile']['username'];	
				}
			}
			if ($query->num_rows()!=0)
				{
					if($this->db->update('prode_cat_user',array(
								'usrName'=>$usrName,
								'usrMail'=>$data['user_profile']['email'],
								'usrCompletName' => $data['user_profile']['name'],
								'fbProfile' => $data['user_profile']['link'],
								'pictureUrl' => $data['usuario'][0]['pic_square']
								), array('fbId' => $data['usuario'][0]['uid'])))
						{
							//nada
							$isUpdate = true;
						}
						else
						{
							return false;
						}
				}
				else
				{
						
				
					if($this->db->insert('prode_cat_user',array(
								'usrName'=>$usrName,
								'usrMail'=>$data['user_profile']['email'],
								'usrCompletName' => $data['user_profile']['name'],
								'fbProfile' => $data['user_profile']['link'],
								'fbId' => $data['usuario'][0]['uid'],
								'pictureUrl' => $data['usuario'][0]['pic_square']
								)))
						{
							//nada
							$isUpdate = false;
						}
						else
						{
							return false;
						}
				}
			
			//Obtener el id del usuario
			$usr  = 0;
			$query = $this->db->get_where('prode_cat_user', array('fbId' => $data['usuario'][0]['uid']));
			if ($query->num_rows()!=0)
				{
				$usr = $query->row('usrId');
				}
					
			if($isUpdate == false)
			{					
				//Obtener el id de la operacion
				$op = 0;
				$query = $this->db->get_where('prode_cat_operation', array('opCode' => 'UR'));
				if ($query->num_rows()!=0)
					{
					$op = $query->row('opId');
					}
					
				//Registrar actividad
				$this->db->insert('prode_cat_activity',array('usrId'=>$usr,'actOp'=>$op,'actDate'=>date('Y-m-d G:i:s')));
			}
			$session = array(
				'username'  => $data['user_profile']['name'],
				'email'     => $data['user_profile']['email'],
				'logged_in' => TRUE,
				'id_user'   => $usr,
				'img'	    => $data['usuario'][0]['pic_square'],
				'fbId'	    => $data['usuario'][0]['uid']
				);
			
			return $session;
		}
	}
	
	function ValidateSession($data = null)
	{
		$query= $this->db->get_where('prode_cat_user',array('usrMail'=>$data['user'], 'usrPass'=>md5($data['pass'])));
		if ($query->num_rows()!=0)
		{
			$newdata = array(
					'username'  => $query->row('usrName'),
					'email'     => $query->row('usrMail'),
					'logged_in' => TRUE,
					'id_user'   => $query->row('usrId'),
					'img'	    => $query->row('pictureUrl'),
					'name'	    => $query->row('usrCompletName'),
					'fbId'	    => $query->row('fbId')
					);
			
			return $newdata;
		}
		else
		{
			return 0;
		}
	}
	
	function GetGroups()
	{
		$usrId = $this->session->userdata('id_user');
		
		//count group
		$this->db->select('prode_cat_group.gpoId, prode_cat_group.gpoName');
		$this->db->from('prode_cat_gpouser');
		$this->db->join('prode_cat_group', 'prode_cat_gpouser.gpoId = prode_cat_group.gpoId');
		$this->db->where('prode_cat_gpouser.usrId', $usrId);
		$this->db->where('prode_cat_gpouser.gpousrStatus', 'AC');
		$group = $this->db->get();
		
		//load all group name's
		$groupList = array();
		foreach($group->result() as $valor)
		{
			$groupList[] = array(
					     'id' => $valor->gpoId,
					     'name' => $valor->gpoName
					     );
		}
		
		return $groupList;
	}
	
	function ReturnGame()
	{
		$query= $this->db->get_where('prode_cat_date',array('dtIsMain'=>1));
		if ($query->num_rows() != 0)
		{
			$data = array();
			$usrId = $this->session->userdata('id_user');
			
			//count group
			$this->db->select('prode_cat_group.gpoId, prode_cat_group.gpoName');
			$this->db->from('prode_cat_gpouser');
			$this->db->join('prode_cat_group', 'prode_cat_gpouser.gpoId = prode_cat_group.gpoId');
			$this->db->where('prode_cat_gpouser.usrId', $usrId);
			$this->db->where('prode_cat_gpouser.gpousrStatus', 'AC');
			$group = $this->db->get();
			
			//load all group name's
			$groupList = array();
			foreach($group->result() as $valor)
			{
				$groupList[] = array(
						     'id' => $valor->gpoId,
						     'name' => $valor->gpoName
						     );
			}
			
			//First group´
			if(!isset($groupList[0]))
			{
				return 0;
			}
			$gpoFirst = $groupList[0]['id'];
			
		
			//Evaluar si hizo o no la jugada
			$dateId = $query->row('dtId');	
			$query = $this->db->get_where('prode_cat_game_format',array('dtId'=>$dateId));
			
			if($gpoFirst != "" && $gpoFirst != null)
			{
				$game = $this->get_matches($query, $gpoFirst, $usrId);
			}
			$data[] = $groupList;
			$data[] = $game;
			return $data;
		}
		else
		{
			return 0;
		}
	}
	
	function ReturnGame_gpo($data = null)
	{
		$query= $this->db->get_where('prode_cat_date',array('dtIsMain'=>1));
		if ($query->num_rows() != 0)
		{
			$dateId = $query->row('dtId');	
			$query = $this->db->get_where('prode_cat_game_format',array('dtId'=>$dateId));
			
			return $this->get_matches($query, $data['gpo'], $this->session->userdata('id_user'));
		}
	}
	
	function get_matches($query, $gpoId, $usrId)
	{
		$game = array();
		
		foreach($query->result() as $valor)
		{
			$jugada = $this->db->get_where('prode_cat_game',array('gfId' => $valor->gfId, 'usrId' => $usrId, 'gpoId' => $gpoId));
			
			if($jugada->num_rows() > 0)
			{
				$game[] = array(
					      'idGame' 		=> $valor->gfId,
					      'local'  		=> $valor->tmIdLocal,
					      'localName'	=> $this->BuscarNombre($valor->tmIdLocal),
					      'localImage'	=> $this->BuscarLogo($valor->tmIdLocal),
					      'visit'		=> $valor->tmIdVisit,
					      'visitName'	=> $this->BuscarNombre($valor->tmIdVisit),
					      'visitImage'	=> $this->BuscarLogo($valor->tmIdVisit),
					      'result' 		=> $jugada->row('gmResult'),
					      'willcard'	=> $jugada->row('gmWillCard')
					      );
			}
			else
			{
				$game[] = array(
					      'idGame' 		=> $valor->gfId,
					      'local'  		=> $valor->tmIdLocal,
					      'localName'	=> $this->BuscarNombre($valor->tmIdLocal),
					      'localImage'	=> $this->BuscarLogo($valor->tmIdLocal),
					      'visit'		=> $valor->tmIdVisit,
					      'visitName'	=> $this->BuscarNombre($valor->tmIdVisit),
					      'visitImage'	=> $this->BuscarLogo($valor->tmIdVisit),
					      'result' 		=> 0,
					      'willcard'	=> $jugada->row('gmWillCard')
					      );
			}
		}
		
		return $game;
	}
	
	function get_result_by_group($data = null)
	{
		$gpoId = $data['gpo'];
		return $this->ReturnResult($gpoId);
	}
	
	function ReturnResult($gpoId)
	{
		$usrId = $this->session->userdata('id_user');
		$query= $this->db->get_where('prode_cat_date',array( 'dtIsMain' => 0 ));
		
		if ($query->num_rows() != 0)
		{
			$results = array();
			
			foreach($query->result() as $valor)
			{
				$puntos = 0;
				
				//Formato de la fecha
				$queryDate = $this->db->get_where('prode_cat_game_format',array( 'dtId' => $valor->dtId ));
				
				foreach($queryDate->result() as $dates)
				{
					
					
					//comparar resultados
					//resultado del game
					$queryGame = $this->db->get_where('prode_cat_game_result',array( 'gfId' => $dates->gfId ));
					$resultado = $queryGame->row('gmResult');
					
					//resultado del usuario
					$queryGameUsr = $this->db->get_where('prode_cat_game',array( 'gfId' => $dates->gfId, 'usrId' => $usrId, 'gpoId' => $gpoId ));
					$resultadoUsr = $queryGameUsr->row('gmResult');
					$resultadoWillCard = $queryGameUsr->row('gmWillCard');
					
					if($resultado == $resultadoUsr || $resultado == $resultadoWillCard)
					{
						$puntos++;
					}
				}
				
				$results[] = array(
							'dtId' 		=> $valor->dtId,
							'dtDescription' => $valor->dtDescription,
							'points' 	=> $puntos
						   );
				
			}
			
			//..................................................................
			//... Region resultado parcial fecha actual ........................
			//..................................................................
			
			//preguntar si termino la fecha actual
			$query= $this->db->get_where('prode_cat_date',array( 'dtIsMain' => 1 ));
			
			if($query->num_rows() != 0)
			{
				$puntos = 0;
				//preguntar si la fecha ya cerro
				if($this->date_limit() == true)
				{
					//mostrar resultados parciales
					//Formato de la fecha
					$queryDate = $this->db->get_where('prode_cat_game_format',array( 'dtId' => $query->row('dtId') ));
					
					foreach($queryDate->result() as $dates)
					{
						//comparar resultados
						//resultado del game
						$queryGame = $this->db->get_where('prode_cat_game_result',array( 'gfId' => $dates->gfId ));
						if($queryGame->num_rows() > 0)
							$resultado = $queryGame->row('gmResult');
							else
							$resultado = -1;
						
						//resultado del usuario
						$queryGameUsr = $this->db->get_where('prode_cat_game',array( 'gfId' => $dates->gfId, 'usrId' => $usrId, 'gpoId' => $gpoId ));
						if($queryGameUsr->num_rows() > 0)
						{
							$resultadoUsr = $queryGameUsr->row('gmResult');
							$resultadoWillCard = $queryGameUsr->row('gmWillCard');
						}
						else
						{
							$resultadoUsr = -2;
							$resultadoWillCard = -2;
						}
						
						if($resultado == $resultadoUsr || $resultado == $resultadoWillCard)
						{
							$puntos++;
						}
					}
						
					$results[] = array(
							'dtId' 		=> $query->row('dtId'),
							'dtDescription' => $query->row('dtDescription'),
							'points' 	=> $puntos
						   );
				}
				
			}
			//..................................................................
			
			return $results;
		}
		else
		{
		     return 0;
		}
	}
	
	
	function BuscarNombre($idTeam)
	{
		$query= $this->db->get_where('prode_cat_team',array('tmId'=>$idTeam));
		
		return $query->row('tmDescription');
	}
	
	
	function BuscarLogo($idTeam)
	{
		$query= $this->db->get_where('prode_cat_team',array('tmId'=>$idTeam));
		
		return $query->row('tmImage');
	}
	
	
	function register_game($data = null)
	{
		if($data == null)
		{
			return json_encode(0);
		}
		else
		{
			//validar que la fecha a jugar no halla cerrado
			//si es igual a la fecha actual, tienen que ser menos de las 18:00 horas
			//si es menor a la fecha actual, no se puede jugar
			//si es mayor a la fecha actual, si se puede jugar
			if($this->date_limit_status() == 0)
			{
				return json_encode(0);
			}
			else
			{
				//preguntar si son menos de las 18:00 horas
				//if( date("G") >= 18 )
				//{
				//	return json_encode(0);
				//}
			}
		
			//id del usuario 
			$usrId = $this->session->userdata('id_user');
			
			//formato de la fecha
			$query= $this->db->get_where('prode_cat_date',array('dtIsMain'=>1));
			$dateId = $query->row('dtId');
			
			if($data['all'] == 'true')
			{
				//repetir para todos los grupos
				$this->db->select('prode_cat_group.gpoId');
				$this->db->from('prode_cat_gpouser');
				$this->db->join('prode_cat_group', 'prode_cat_gpouser.gpoId = prode_cat_group.gpoId');
				$this->db->where('prode_cat_gpouser.usrId', $usrId);
				$this->db->where('prode_cat_gpouser.gpousrStatus', 'AC');
				$group = $this->db->get();
				
				//load all group name's
				$groupList = array();
				foreach($group->result() as $gpo)
				{
					//$valor->gpoId
					//Evaluar si hizo o no la jugada
					$query = $this->db->get_where('prode_cat_game_format',array('dtId'=>$dateId));
					$insert = true;
					
					foreach($query->result() as $valor)
					{
						$jugada = $this->db->get_where('prode_cat_game',array('gfId'=>$valor->gfId,'usrId'=> $usrId, 'gpoId' => $gpo->gpoId));
						
						if($jugada->num_rows() > 0)
						{
							$insert = false;
							break;
						}
					}
					
					if($insert == true)
					{
						$willcard = $data['xwillcard'];
					
						$indice = 0;
						foreach($data['xnames'] as $valor)
						{
							if($valor == $willcard[0])
							{
								if($this->db->insert('prode_cat_game',array('usrId'=>$usrId, 'gfId'=>$valor, 'gmResult'=>$data['xsites'][$indice], 'gmWillCard' => $willcard[1], 'gpoId' => $gpo->gpoId )) == false)
										{
										     return json_encode(0);
										}
							}
							else
							{
								if($valor == $willcard[2])
								{
									if($this->db->insert('prode_cat_game',array('usrId'=>$usrId, 'gfId'=>$valor, 'gmResult'=>$data['xsites'][$indice], 'gmWillCard' => $willcard[3], 'gpoId' => $gpo->gpoId)) == false)
										{
										     return json_encode(0);
										}
								}
								else
								{
									if($this->db->insert('prode_cat_game',array('usrId'=>$usrId, 'gfId'=>$valor, 'gmResult'=>$data['xsites'][$indice], 'gpoId' => $gpo->gpoId)) == false)
										{
										     return json_encode(0);
										}		
								}
							}
					
							$indice++;
						}
						
						//Obtener el id de la operacion
						$op = 0;
						$query = $this->db->get_where('prode_cat_operation', array('opCode' => 'CG'));
						if ($query->num_rows()!=0)
							{
							$op = $query->row('opId');
							}
							
						//Registrar actividad
						$this->db->insert('prode_cat_activity',array('usrId'=>$usrId,'actOp'=>$op,'actDate'=>date('Y-m-d G:i:s')));
					}
					else
					{
						$willcard = $data['xwillcard'];
					
						$indice = 0;
						foreach($data['xnames'] as $valor)
						{
							if($willcard[0] == $valor)
							{
								if($this->db->update('prode_cat_game',array('gmResult'=>$data['xsites'][$indice], 'gmWillCard'=>$willcard[1]),array('usrId'=>$usrId, 'gfId'=>$valor, 'gpoId' => $gpo->gpoId)) == false)
									{
									     return json_encode(0);
									}
							}
							else
							{
								if($willcard[2] == $valor)
								{
									if($this->db->update('prode_cat_game',array('gmResult'=>$data['xsites'][$indice], 'gmWillCard'=>$willcard[3]),array('usrId'=>$usrId, 'gfId'=>$valor, 'gpoId' => $gpo->gpoId)) == false)
									{
									     return json_encode(0);
									}
								}
								else
								{
									if($this->db->update('prode_cat_game',array('gmResult'=>$data['xsites'][$indice], 'gmWillCard'=>null),array('usrId'=>$usrId, 'gfId'=>$valor, 'gpoId' => $gpo->gpoId)) == false)
									{
									     return json_encode(0);
									}		
								}
							}
							   
							$indice++;
						}
						
						//Obtener el id de la operacion
						$op = 0;
						$query = $this->db->get_where('prode_cat_operation', array('opCode' => 'UG'));
						if ($query->num_rows()!=0)
							{
								$op = $query->row('opId');
							}
							
						//Registrar actividad
						$this->db->insert('prode_cat_activity',array('usrId'=>$usrId,'actOp'=>$op,'actDate'=>date('Y-m-d G:i:s')));
					}
				}
				
				return json_encode(1);
			}
			else
			{
				//Actualizar solo el grupo seleccionado 
				$gpoId = $data['gpoId'];
				$query = $this->db->get_where('prode_cat_game_format',array('dtId'=>$dateId));
				$insert = true;
				
				foreach($query->result() as $valor)
				{
					$jugada = $this->db->get_where('prode_cat_game',array('gfId'=>$valor->gfId,'usrId'=>$usrId, 'gpoId' => $gpoId));
					
					if($jugada->num_rows() > 0)
					{
						$insert = false;
						break;
					}
				}
				
				if($insert == true)
				{
					$willcard = $data['xwillcard'];
				
					$indice = 0;
					foreach($data['xnames'] as $valor)
					{
						if($valor == $willcard[0])
						{
							if($this->db->insert('prode_cat_game',array('usrId'=>$usrId, 'gfId'=>$valor, 'gmResult'=>$data['xsites'][$indice], 'gmWillCard' => $willcard[1], 'gpoId' => $gpoId )) == false)
									{
									     return json_encode(0);
									}
						}
						else
						{
							if($valor == $willcard[2])
							{
								if($this->db->insert('prode_cat_game',array('usrId'=>$usrId, 'gfId'=>$valor, 'gmResult'=>$data['xsites'][$indice], 'gmWillCard' => $willcard[3], 'gpoId' => $gpoId)) == false)
									{
									     return json_encode(0);
									}
							}
							else
							{
								if($this->db->insert('prode_cat_game',array('usrId'=>$usrId, 'gfId'=>$valor, 'gmResult'=>$data['xsites'][$indice], 'gpoId' => $gpoId)) == false)
									{
									     return json_encode(0);
									}		
							}
						}
				
						$indice++;
					}
					
					//Obtener el id de la operacion
					$op = 0;
					$query = $this->db->get_where('prode_cat_operation', array('opCode' => 'CG'));
					if ($query->num_rows()!=0)
						{
							$op = $query->row('opId');
						}
						
					//Registrar actividad
					$this->db->insert('prode_cat_activity',array('usrId'=>$usrId,'actOp'=>$op,'actDate'=>date('Y-m-d G:i:s')));
				}
				else
				{
					$willcard = $data['xwillcard'];
					$indice = 0;
					foreach($data['xnames'] as $valor)
					{
						if($willcard[0] == $valor)
						{
							if($this->db->update('prode_cat_game',array('gmResult'=>$data['xsites'][$indice], 'gmWillCard'=>$willcard[1]),array('usrId'=>$usrId, 'gfId'=>$valor, 'gpoId' => $gpoId)) == false)
								{
								     return json_encode(0);
								}
						}
						else
						{
							if($willcard[2] == $valor)
							{
								if($this->db->update('prode_cat_game',array('gmResult'=>$data['xsites'][$indice], 'gmWillCard'=>$willcard[3]),array('usrId'=>$usrId, 'gfId'=>$valor, 'gpoId' => $gpoId)) == false)
								{
								     return json_encode(0);
								}
							}
							else
							{
								if($this->db->update('prode_cat_game',array('gmResult'=>$data['xsites'][$indice], 'gmWillCard'=>null),array('usrId'=>$usrId, 'gfId'=>$valor, 'gpoId' => $gpoId)) == false)
								{
								     return json_encode(0);
								}		
							}
						}
						   
						$indice++;
					}
					
					//Obtener el id de la operacion
					$op = 0;
					$query = $this->db->get_where('prode_cat_operation', array('opCode' => 'UG'));
					if ($query->num_rows()!=0)
						{
						$op = $query->row('opId');
						}
						
					//Registrar actividad
					$this->db->insert('prode_cat_activity',array('usrId'=>$usrId,'actOp'=>$op,'actDate'=>date('Y-m-d G:i:s')));
				}
				
				return json_encode(1);
			}
			
			return json_encode(1);
		}
	}
	
	
	
	//Compara si la fecha1 es mayor a la fecha2
	//si fecha1 > fecha2 = true
	//sino fecha1 <= fecha2 = false
	function comp_date($fecha1, $fecha2)
	{
		/*
		$fecha1 = str_replace('/','-',$fecha1);
		
		list($dia,$mes,$año)=explode('-',$fecha1);
		
		$fecha1 = mktime(0,0,0,$mes,$dia,$año);
		
		list($dia,$mes,$año)=explode('-',$fecha2);
		
		$fecha2 = mktime(0,0,0,$mes,$dia,$año);
	
		if($fecha1 > $fecha2)
		{
			return true;
		}
		else
		{
			return false;
		}*/
		echo "puto";
	}
	
	
	function date_limit()
	{
		$query= $this->db->get_where('prode_cat_date',array('dtIsMain'=>1));
		if ($query->num_rows() != 0)
		{
			$date = $query->row('dtDayLimit');
			$fecha2 = date("Y-m-d"); 
			
			$fecha1 = str_replace('/','-',$date);
			
			//$fecha1 => fecha limite de juego
			//$fecha2 => fecha actual
			
			if($fecha1 > $fecha2)
			{
				return false;
			}
			else
			{
				if($fecha1 == $fecha2)
				{
					//preguntar si son menos de las 18:00 horas
					if( date("G") >= 18 )
					{
						return true;
					}
					else
					{
						return false;
					}
				}
				else
				{
					return true;
				}
			}
		}
		else
		{
			return false;
		}
	}
	
	function date_limit_status()
	{
		$query= $this->db->get_where('prode_cat_date',array('dtIsMain'=>1));
		if ($query->num_rows() != 0)
		{
			$date = $query->row('dtDayLimit');
			$fecha2 = date("Y-m-d"); 
			
			$fecha1 = str_replace('/','-',$date);
			
			if($fecha1 > $fecha2)
			{
				return 2;
			}
			else
			{
				if($fecha1 == $fecha2)
				{
					return 1;
				}
				else
				{
					return 0;
				}
				
			}
		}
		else
		{
			return 0;
		}
	}
	
	function return_date()
	{
		$query= $this->db->get_where('prode_cat_date',array('dtIsMain'=>1));
		if ($query->num_rows() != 0)
		{
			return $query->row('dtDayLimit');
		}
		else
		{
			return false;
		}
	}
	
	function update_profile($data = null)
	{
		if($data == null)
		{
			return false;
		}
		else
		{
			$indice = 0;
			$insert = array();
			
			foreach($data['xrefere'] as $valor)
			{
				switch($valor)
				{
					case "usrname":
						$insert['usrCompletName'] = $data['xvalue'][$indice];
						$indice++;
						break;
					
					case "pass":
						$insert['usrPass'] = md5($data['xvalue'][$indice]);
						$indice++;
						break;
				}
			}
			
			if( $indice > 0 )
			{
				//id del usuario 
				$usrId = $this->session->userdata('id_user');
				$this->db->where('usrId', $usrId);
				
				
				if($this->db->update('prode_cat_user', $insert) == false)
				{
					return 0;
				}
				else
				{
					return 1;
				}
			}
			else
			{
				return 1;
			}
			
			
		}
	}
	
	function set_user_status($data = null)
	{
		if($data == null)
		{
			return false;	
		}
		else
		{
			$id = $data['id'];
			$insert['gpousrStatus'] = 'IN';
			if($data['status'] == 1)
			{
				$insert['gpousrStatus'] = 'AC';
			}
			
			$this->db->where('gpousrId', $id);
				
				
			if($this->db->update('prode_cat_gpouser', $insert) == false)
			{
				return 0;
			}
			else
			{
				//Send mail
				return 1;
			}
		}
	}
	function date_of_user($data = null)
	{
		if($data == null)
		{
			return false;	
		}
		else
		{
			$usrId = $this->session->userdata('id_user');
			$fecha = $data['fecha'];
			$gpoId = $data['gpo'];
			
			return $this->return_result_for_user($fecha, $usrId, $gpoId);
			
		}
	}
	
	function date_of_user_results($data = null)
	{
		if($data == null)
		{
			return false;	
		}
		else
		{
			$usrId = $data['usr'];
			$fecha = $data['fecha'];
			
			return $this->return_result_for_user($fecha, $usrId);
			
		}
	}
	
	function return_result_for_user($fecha , $usrId, $gpoId)
	{			
		//Evaluar si hizo o no la jugada
		$query = $this->db->get_where('prode_cat_game_format',array('dtId'=>$fecha));
		
		$game = array();
		
		foreach($query->result() as $valor)
		{
			$jugada = $this->db->get_where('prode_cat_game',array('gfId'=>$valor->gfId,'usrId'=>$usrId, 'gpoId'=>$gpoId));
			
			if($jugada->num_rows() > 0)
			{
				$game[] = array(
					      'localName'	=> $this->BuscarNombre($valor->tmIdLocal),
					      'localImage'	=> $this->BuscarLogo($valor->tmIdLocal),
					      'visitName'	=> $this->BuscarNombre($valor->tmIdVisit),
					      'visitImage'	=> $this->BuscarLogo($valor->tmIdVisit),
					      'resultUsr'	=> $jugada->row('gmResult'),
					      'resultFin'	=> $this->BuscarResultado($valor->gfId),
					      'willCard'	=> $jugada->row('gmWillCard')
					      );
			}
		}
		
		return $game;

	}
	
	function BuscarResultado($idDate)
	{
		$query= $this->db->get_where('prode_cat_game_result',array('gfId'=>$idDate));
		
		if($query->num_rows() > 0)
			return $query->row('gmResult');
		else
			return -1;
	}
	
	function Estadistic_team($data = null)
	{
		if($data == null)
		{
			return false;	
		}
		else
		{
			$team 		= $data['team'];
			$condicion 	= $data['est'];
			
			$query = $this->db->get_where('prode_cat_team', array('tmDescription' => $team));
			
			$mainDate = $this->db->get_where('prode_cat_date', array('dtIsMain' => 1));
			
			$idFecha = 0;
			if($mainDate->num_rows() > 0)
			{
				$idFecha = $mainDate->row('dtId');	
			}			
			
			if($query->num_rows() > 0)
			{
				$idTeam = $query->row('tmId');
				$this->db->where('(tmIdLocal = '.$query->row('tmId').' or tmIdVisit = '.$query->row('tmId').') and dtId != '.$idFecha.' ');
				$query = $this->db->get('prode_cat_game_format');
				
				if($query->num_rows() > 0)
				{
					$partidos 	= 0;
					$ganados 	= 0;
					$ganadosLoc	= 0;
					$ganadosVis	= 0;
					$empatados 	= 0;
					$empatadosLoc	= 0;
					$empatadosVis	= 0;
					$perdidos 	= 0;
					$perdidosLoc	= 0;
					$perdidosVis	= 0;
					
					$partidos = $query->num_rows();
					
					foreach($query->result() as $valor)
					{
						$resultado = $this->db->get_where('prode_cat_game_result',array('gfId'=>$valor->gfId));
						
						if($resultado->num_rows() > 0)
						{
							$res = $resultado->row('gmResult');
							
							switch($res)
							{
								//Empate
								case 0:
									$empatados++;
									if($valor->tmIdLocal == $idTeam)
									{
										$empatadosLoc++;
									}
									else
									{
										$empatadosVis++;
									}
									break;
								
								//Local
								case 1:
									if($valor->tmIdLocal == $idTeam)
									{
										$ganados++;
										$ganadosLoc++;
									}
									else
									{
										$perdidos++;
										$perdidosLoc++;
									}
									break;
								
								//Visitante
								case 2:
									if($valor->tmIdVisit == $idTeam)
									{
										$ganados++;
										$ganadosVis++;
									}
									else
									{
										$perdidos++;
										$perdidosVis++;
									}
									break;
							}
						}
					}
					
					$array = 	array(	'ganados' 	=> $ganados, 
								'ganadosLoc' 	=> $ganadosLoc,
								'ganadosVis'	=> $ganadosVis,
								'empatados' 	=> $empatados,
								'empatadosLoc'  => $empatadosLoc,
								'empatadosVis'  => $empatadosVis,
								'perdidos' 	=> $perdidos,
								'perdidosLoc' 	=> $perdidosLoc,
								'perdidosVis'	=> $perdidosVis,
								'partidos'	=> $partidos);
					
					return $array;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return 0;
			}
		}
	}
	
	function Groups()
	{
		$usrId = $this->session->userdata('id_user');
		$group = array();
		$query = $this->db->get_where('prode_cat_group', array('usrId' => $usrId));
		
		$group['my'] = $query->result_array();	
		
		$this->db->select('prode_cat_group.gpoId, prode_cat_group.gpoName');
		$this->db->from('prode_cat_gpouser');
		$this->db->join('prode_cat_group', 'prode_cat_gpouser.gpoId = prode_cat_group.gpoId');
		$this->db->where('prode_cat_gpouser.usrId', $usrId);
		$this->db->where('prode_cat_gpouser.gpousrStatus', 'AC');
		$query = $this->db->get();
		
		$group['game'] = $query->result_array();
		
		return $group;
	}
	
	function GetGroupsAdmin()
	{
		$usrId = $this->session->userdata('id_user');
		$group = array();
		$query = $this->db->get_where('prode_cat_group', array('usrId' => $usrId));
		
		foreach($query->result() as $g)
		{
			$this->db->select('Count(*) as cant');
			$this->db->from('prode_cat_gpouser');
			$this->db->where('gpoId', $g->gpoId);
			$cant = $this->db->get();
			$c = $cant->result_array();
			
			$group['groups'][] = array(
				'gpoName' 		=> $g->gpoName,
				'gpoMaxCompetitors' 	=> $g->gpoMaxCompetitors,
				'gpoId'			=> $g->gpoId,
				'gpoCant'		=> $c
			);
			
		}
		
		//$group['groups'] = $query->result_array();
		return $group;
	}
	
	function Get_users_by_Groups($data = null)
	{
		$gpoId = $data['gpo'];
		
		$this->db->select('prode_cat_gpouser.gpousrId, prode_cat_gpouser.gpousrStatus, prode_cat_user.usrName, prode_cat_user.usrCompletName, prode_cat_user.usrMail, prode_cat_user.pictureUrl');
		$this->db->from('prode_cat_gpouser');
		$this->db->join('prode_cat_user', 'prode_cat_gpouser.usrId = prode_cat_user.usrId');
		$this->db->where('prode_cat_gpouser.gpoId', $gpoId);
		$query = $this->db->get();
		
		$users = $query->result_array();
		
		return $users;
	}
	
	function Get_users_facebook_friends()
	{
		$this->appId = '712944462084224';
		$this->secret = '58b2806877539684ebedfbe88cb9d226';
		$fb_config = array(
		    'appId' => $this->appId,
		    'secret' => $this->secret
		);
		$this->load->library('facebook', $fb_config);
		
		$user_id = $this->facebook->getUser();
		$token = $this->facebook->getAccessToken();
		
		$friends = $this->facebook->api("/me/friends?fields=id,name,picture");
		return $friends;
		
		
		
		//$word = "Sergio";
		//$hashtags = $this->facebook->api('/search?q='.$word.'&type=user&limit=10');
		//$hashtags = $this->facebook->api('/100005539067906/message');
		//return $hashtags;
	}
	
	function SendInvitation($data = null)
	{
		$insert = array();
		$insert['usrFbId'] = $data['fbId'];
		$insert['gpoId'] = $data['gpoId'];
		$insert['status'] = 'PN';
		
		//var_dump($data);
		
		if($this->db->insert('prode_cat_invitation', $insert) == false)
		{
			return 0;
		}
		else
		{
			//ENviar mail para cooregir el tema de las solicitudes
			//$to = $insert['usrFbId']."@facebook.com";
			//$from = $this->session->userdata('name')." te invito a jugar.";
			//
			//$message = 
			//
			//mail($to,$from,'Esto es una prueba','','');
			
			/* Esto me lo rebota 
			$config['useragent'] = 'CodeIgniter';
			$config['protocol'] = 'smtp';
			//$config['mailpath'] = '/usr/sbin/sendmail';
			$config['smtp_host'] = 'ssl://smtp.googlemail.com';
			$config['smtp_user'] = 'eseeme51@gmail.com';
			$config['smtp_pass'] = 'sergio.claudia';
			$config['smtp_port'] = 465; 
			$config['smtp_timeout'] = 5;
			$config['wordwrap'] = TRUE;
			$config['wrapchars'] = 76;
			$config['mailtype'] = 'html';
			$config['charset'] = 'utf-8';
			$config['validate'] = FALSE;
			$config['priority'] = 3;
			$config['crlf'] = "\r\n";
			$config['newline'] = "\r\n";
			$config['bcc_batch_mode'] = FALSE;
			$config['bcc_batch_size'] = 200;
			*/
			
			//$config = Array(
			//	'protocol' => 'smtp',
			//	'smtp_host' => 'ssl://smtp.googlemail.com',
			//	'smtp_port' => 465,
			//	'smtp_user' => 'eseeme51@gmail.com',
			//	'smtp_pass' => 'sergio.claudia',
			//	'mailtype'  => 'html', 
			//	'charset'   => 'iso-8859-1'
			//);
			//$this->load->library('email', $config);
			
			$body = '
			<div style="height: 330px; width: 500px; background: #A4A4A4; border-radius: 10px; border-color: black; border-width: 1px; border-style: solid; font-family: sans-serif;">
				<table style="width: 100%; height: 100%; color: #E6E6E6;">
				    <tr>
					<td style="width: 50%; text-align: center;">
					    <h2>Prode del Fútbol</h2>
					</td>
					<td style="width: 50%; height: 200px; background-color: none; padding-top: 5px; padding-left: 40px;">
						    <img height="190px;" src="http://prode.indev.com.ar/assets/img/mainPage/user.png">
					</td>
				    </tr>
				    <tr>
					<td colspan="2">
					    Tenes una invitación de '.$this->session->userdata('username').' para unirte y jugar en su grupo de prode.
					</td>
				    </tr>
				    <tr>
					<td colspan="2" style="text-align: center">
					    <center>
					    <div style="border-radius: 15px; background: #BEF781; border-width: 1px; border-style: solid; border-color: #4B8A08; height: 60px; width: 150px;"><br><a href="http://prode.indev.com.ar/login" style="cursor: pointer; text-decoration:none; padding-top: 5px;"><strong>Aceptar invitación</strong></a></div>
					    </center>
					</td>
				    </tr>
				    <tr>
					<td><br></td>
				    </tr>
				</table>
			    </div>
			';
			$config['mailtype'] = 'html';
			$this->load->library('email', $config);
			$this->email->set_newline("\r\n");
			    
			$this->email->from('prode@indev.com.ar', 'Prode del Fútbol');
			$this->email->to($data['fbId'].'@facebook.com'); 
		
			$this->email->subject('Invitación para jugar al prode de '.$this->session->userdata('username') );
			$this->email->message($body);  
		
			$result = $this->email->send();
			
			//return $result;
			
			////////Envia pero no deseado 
			////////$this->load->library('email');
			////////$this->load->library('parser');
			////////$this->email->clear();
			////////$config['mailtype'] = "html";
			////////$this->email->initialize($config);
			////////$this->email->set_newline("\r\n");
			////////$this->email->from('sergio.moyano@example.com', 'Website');
			////////$list = array('eseeme51@hotmail.com', 'sergio.moyano@outlook.com.ar');
			////////$this->email->to($list);
			////////$data = array();
			//////////$htmlMessage = $this->parser->parse('messages/email', $data, true);
			////////$this->email->subject('This is an email test');
			////////$this->email->message("hola Manola");
			////////   
			////////   
			////////   
			////////if ($this->email->send()) {
			////////    echo 'Your email was sent, thanks chamil.';
			////////} else {
			////////    show_error($this->email->print_debugger());
			////////}
			
			
		//	$this->appId = '712944462084224';
		//	$this->secret = '58b2806877539684ebedfbe88cb9d226';
		//	$fb_config = array(
		//	    'appId' => $this->appId,
		//	    'secret' => $this->secret
		//	);
		//	$this->load->library('facebook', $fb_config);
		//	
		//	$user_id = $this->facebook->getUser();
		//	$token = $this->facebook->getAccessToken();
		//	
		//	//---------Enviar solicitud----------(pero tiene que tener los permisos de la app)
		//        $accessToken = $this->appId . '|' . $this->secret;
		//	$canvasPage = 'https://apps.facebook.com/712944462084224/';
		//	$message = '@['.$this->session->userdata('fbId').'] te invito a unirse a su grupo de prode. Ingresa en prode.indev.com.ar!!';
		//	$params = array(
		//		    'access_token' => $accessToken,
		//		    'href' => $canvasPage,
		//		    'template' => $message
		//		);
			//$this->facebook->api('/100005539067906/notifications', 'POST',$params);
			//----------end----------------------
			
			
			
			//$this->facebook->api('/'.$data['fbId'].'/notifications', 'POST',$params);
			
			//$uid = "1215802892"; //User's Facebook ID, set the value as "me" if publishing on logged in user's wall
			//$ufname = "Sergio Moyano"; // User's Full name on Facebook
			
			//---------Postear en el muro del usuario----- (pero tiene que tener los permisos de la app)
			//$attachment =  array(
				//'access_token' => $accessToken,
				//'message' => "Tenes una invitación de @[".$uid."]&!", //Mensaje
				//'name' => "Sergio Test",							//Nombre de la aplicación o sitio.
				//'link' => "http://prode.indev.com.ar/login",					//Link a donde redireccionar.				
				//'description' => "Prode de Fútbol Argento", 					//Nombre de la app que postea.  
				//'picture' => 'http://5oymexico.org/wp-content/uploads/2013/04/SOBRE-correo.jpg', //Imagen para mostrar en miniatura.
				//'caption' => 'http://prode.indev.com.ar'
			//);
			    
			//facebook->api('/'.$uesr_id.'/feed', 'POST', $attachment);
			//$this->facebook->api('/100005539067906/feed', 'POST',$attachment);
			//$this->facebook->api("/{message-id}");
			//----------end-------------------------
			
			//$uid = "100005539067906"; //User's Facebook ID, set the value as "me" if publishing on logged in user's wall
			//$ufname = "Usuario Prueba"; // User's Full name on Facebook
			//$attachment = array(
			//'message'=> "Happy Birthday, @[".$uid.":1:".$ufname."]!",
			//);
			//
			//$this->facebook->api('/'.$uid.'/feed', 'POST', $attachment);
			//
			return 1;
		}
		
		//
	}
	
	function getInvitations()
	{
		$UsrFbId = $this->session->userdata('fbId');
		
		$this->db->select('prode_cat_invitation.idInvit, prode_cat_invitation.status, prode_cat_group.gpoName');
		$this->db->from('prode_cat_invitation');
		$this->db->join('prode_cat_group', 'prode_cat_invitation.gpoId = prode_cat_group.gpoId');
		$this->db->where('prode_cat_invitation.usrFbId', $UsrFbId);
		$query = $this->db->get();
		
		return $query->result_array();	
	}
	
	function set_user_invitation($data = null)
	{
		if($data['action'] == 0)
		{
			if($this->db->update('prode_cat_invitation',array('status'=>'RE'),array('idInvit'=>$data['id'])) == false)
			{
				return 0;
			}
			else
			{
				return 1;
			}
		}
		else
		{
			//buscar el identificador del grupo
			$query = $this->db->get_where('prode_cat_invitation', array('idInvit' => $data['id']));
			if($query->num_rows() > 0)
			{
				$idGpo = $query->row('gpoId');
				
				$this->db->select('Count(*) as cant');
				$this->db->from('prode_cat_gpouser');
				$this->db->where('gpoId', $idGpo);
				$cant = $this->db->get();
				$c = $cant->result_array();
				$cantActual = $c[0]['cant'];
				
				$query = $this->db->get_where('prode_cat_group', array('gpoId' => $idGpo));
				if($query->num_rows() > 0)
				{
					$cantMax = $query->row('gpoMaxCompetitors');
					
					if($cantActual < $cantMax)
					{
						$insert = array();
						$insert['usrId'] = $this->session->userdata('id_user');
						$insert['gpoId'] = $idGpo;
						$insert['gpousrStatus'] = 'AC';
						
						//ver si ya esta en el grupo
						$duplicado = $this->db->get_where('prode_cat_gpouser', array('gpoId' => $idGpo, 'usrId' => $this->session->userdata('id_user')));
						if($query->num_rows() > 0)
						{
							if($this->db->update('prode_cat_invitation',array('status'=>'AC'),array('idInvit'=>$data['id'])) == false)
							{
								return 0;
							}
							else
							{
								return 1;
							}
						}
						else
						{
							if($this->db->insert('prode_cat_gpouser', $insert) == false)
							{
								return 0;
							}
							else
							{
								if($this->db->update('prode_cat_invitation',array('status'=>'AC'),array('idInvit'=>$data['id'])) == false)
								{
									return 0;
								}
								else
								{
									return 1;
								}
							}
						}
					}
					else
					{
						if($this->db->update('prode_cat_invitation',array('status'=>'CO'),array('idInvit'=>$data['id'])) == false)
						{
							return 0;
						}
						else
						{
							return 1;
						}	
					}
				}
				else
				{return 0;}
				
			}
			else
			{ return 0; }
			
		}
	}
	
	function validateNewGroup($data = null)
	{
		
		$query = $this->db->get_where('prode_cat_group', array('gpoName' => $data['group']));
		if($query->num_rows() > 0)
		{
			//El nombre no esta disponible
			return 2;
		}
		else
		{
			$insert = array();
			$insert['gpoName'] = $data['group'];
			$insert['usrId'] = $this->session->userdata('id_user');
			$insert['gpoMaxCompetitors'] = 10;
			$insert['gpoStatus'] = 'AC';
			
			if($this->db->insert('prode_cat_group', $insert) == false)
			{
				return 0;
			}
			else			
			{
				$insert_user_group = array();
				$insert_user_group['usrId'] = $this->session->userdata('id_user');
				$insert_user_group['gpoId'] = $this->db->insert_id();
				$insert_user_group['gpousrStatus'] = 'AC';
				$this->db->insert('prode_cat_gpouser', $insert_user_group);
				
				return 1;
			}
		}
	}
}
	